<?php
/**
 * Zhub - A PHP Framework For API Developer
 *
 * This file is part of the Zhub package.
 *
 * (c) YiLong Fan <fantiq@163.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author fanyilong <fantiq@163.com>
 * @copyright 2017 fanyilong. All rights reserved.
 * @package Zhub
 * @date 18-3-7
 */

namespace Zhub\DataBase\Grammar\MySQL;


use Zhub\DataBase\Grammar\Exceptions\InvalidFieldIndexException;
use Zhub\DataBase\Grammar\Grammar;

class Insert extends Grammar
{
    const FIELDS = 1;

    const VALUES = 2;

    private $index = 0;

    public function select(string ...$fields):self
    {
        $this->sqlComponent[self::FIELDS] = $fields;
        return $this;
    }

    public function value(...$row):self
    {
        $value = [];
        foreach ($row as $idx => $value) {
            $fieldName = $this->getFieldNameByIdx($idx);
            if (!$fieldName) {
                throw new InvalidFieldIndexException();
            }
            $value[] = $fieldName = ":{$fieldName}_{$this->index}";
            $this->bindValue(":$fieldName", $value);
        }

        $value = implode(',', $value);

        ++$this->index;

        $this->sqlComponent[self::VALUES][] = "($value)";
        return $this;
    }

    public function values(array $rows)
    {
        foreach ($rows as $row) {
            $this->value($row);
        }
    }

    protected function getFieldNameByIdx(int $idx):?string
    {
        return $this->sqlComponent[self::FIELDS][$idx]??null;
    }

    public function toSQL():string
    {
        $sql = "INSERT INTO%s(%s) VALUES%s";
        return sprintf($sql,
            $this->tableName,
            implode(',', $this->sqlComponent[self::FIELDS]),
            implode(',', $this->sqlComponent[self::VALUES]));
    }

    public function initialize()
    {
        parent::initialize();

        $this->sqlComponent = [
            self::FIELDS => [],
            self::VALUES => [],
        ];
    }
}
